package com.example.admin.testdemo.util;

import android.text.TextUtils;
import android.util.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 转换工具类
 */
public class ConvertUtils {

    /**
     * 对象转换为base64字符串
     *
     * @param object
     * @return
     */
    public static String object2Base64(Object object) {
        String base64 = null;
        if (object == null) {
            return null;
        }
        ByteArrayOutputStream byteOut = null;
        ObjectOutputStream objectOut = null;
        try {
            byteOut = new ByteArrayOutputStream();
            objectOut = new ObjectOutputStream(
                    byteOut);
            objectOut.writeObject(object);
            byte[] arr = byteOut.toByteArray();
            // 转为base64字符串
            base64 = Base64.encodeToString(arr, Base64.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeStream(objectOut);
            closeStream(byteOut);
        }
        return base64;
    }

    /**
     * base64转为对象
     *
     * @param base64
     * @return
     */
    public static Object base642Object(String base64) {
        Object o = null;
        if (TextUtils.isEmpty(base64)) {
            return o;
        }
        ByteArrayInputStream byteIn = null;
        ObjectInputStream objectIn = null;
        try {
            byte[] arr = Base64.decode(base64, Base64.DEFAULT);
            byteIn = new ByteArrayInputStream(arr);
            objectIn = new ObjectInputStream(byteIn);
            o = objectIn.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeStream(objectIn);
            closeStream(byteIn);
        }
        return o;
    }

    /**
     * 关闭流
     *
     * @param closeable
     */
    private static void closeStream(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}